package com.quyunshuo.module.home.activity.main

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import com.quyunshuo.module.home.room.dao.StepsDao
import com.quyunshuo.module.home.room.entity.Steps
import com.quyunshuo.module.home.util.appLifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

// StepCounterManager.kt
@SuppressLint("StaticFieldLeak")
/**
 * 计步管理器单例类
 * 使用 Android 内置计步传感器实现计步功能
 * 通过 StateFlow 提供步数数据流，支持协程收集
 */

object StepCounterManager {
    // 日期处理

    // 上下文和传感器相关变量
    private lateinit var context: Context
    private lateinit var sensorManager: SensorManager
    private var stepSensor: Sensor? = null

    // 步数数据流
    private var _stepCount = MutableStateFlow<Long?>(null)
    val stepCount = _stepCount.asStateFlow()

    // 状态变量
    private var isListening = false
    private var lastTotalSteps = 0
    private var lastSaveTime = 0L

    // 传感器事件监听器
    private val sensorEventListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent?) {
            event?.let {
                if (it.sensor.type == Sensor.TYPE_STEP_COUNTER) {
                    val totalSteps = it.values[0].toLong()
                    Log.d("StepCounter", "onSensorChanged: $totalSteps")
                    appLifecycleScope.launch {
                        handleStepCount(totalSteps)

                    }
                }
            }
        }

        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
            // 不需要处理
        }
    }

    /**
     * 初始化计步管理器
     * @param context 应用上下文
     * @param dao Room数据库的StepsDao
     * @param coroutineScope 协程作用域
     */
    fun initialize(context: Context) {
        this.context = context.applicationContext

        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)

    }

    /**
     * 开始监听计步传感器
     */
    fun startListening() {
        if (isListening || stepSensor == null) return

        stepSensor?.let {
            sensorManager.registerListener(
                sensorEventListener,
                it,
                SensorManager.SENSOR_DELAY_UI
            )
            isListening = true
        }
    }

    /**
     * 停止监听计步传感器
     */
    fun stopListening() {
        if (!isListening) return

        sensorManager.unregisterListener(sensorEventListener)
        isListening = false
    }

    /**
     * 处理计步传感器返回的步数数据
     * @param totalSteps 传感器返回的总步数
     */
    private suspend fun handleStepCount(totalSteps: Long?) {

        // 更新当天步数
        _stepCount.emit(totalSteps)
    }


    /**
     * 检查设备是否支持计步传感器
     */
    fun isSensorAvailable(): Boolean {
        return stepSensor != null
    }

    /**
     * 获取当天开始时间（00:00:00）
     */
    private fun getStartOfDay(): Date {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.time
    }
}